package com.zhiqianbao.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.moblie.zmxy.antgroup.creditsdk.app.CreditApp;
import com.zhiqianbao.R;
import com.zhiqianbao.credit.sdk.DemoPresenter;
import com.zhiqianbao.credit.sdk.DemoView;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.Constants;
/**
 * Created by 子龙 on 2017/4/10.
 * 淘宝网授权
 */

public class TaoBaoActivity extends BaseActivity implements DemoView,View.OnClickListener {
    private TextView topbar_textview_title;
    private Button button_return;
    //账号
    private EditText account_tv;
    //密码
    private EditText et_password;
    //登录
    private Button bt_login;
    //输入的账号
    private String account;
    //输入的密码
    private String pssword;
    private DemoPresenter presenter;
    //短信验证码
    private LinearLayout message12;
    //图片验证码
    private LinearLayout ll_image;
    //扫描二维码
    private LinearLayout online_pay;
    private View line2;
    //短信验证码
    private EditText editTxt_msg;
    private  SharedPreferanceUtils sharedPreferanceUtils;
//    private ImageView ;
    //支付宝验证码
    private String codeX;
    private String sid;
    private  String msg;
    //验证码的状态
    private String type;
    //图片验证码
    private ImageView editTxt_iamge;
    private EditText pay_iamge;
    private String msg_lv;
//    private View view_line1;
    private Button bt_skip;
    private ImageView lv_msg;
    private Dialog dialog;
    private ImageView mImageView;
    //二维码图片
    private Bitmap bitmap_code;
    private String   in_nocode;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.taobao);
        //init presenter
        presenter = new DemoPresenterImpl(this, this);

        initView();
        initData();
        addListNer();
    }

    private void initData() {
         account = account_tv.getText().toString().trim();
        pssword = et_password.getText().toString().trim();
      sharedPreferanceUtils = new SharedPreferanceUtils(this);

    }

    private void initView() {
        ll_image = (LinearLayout) findViewById(R.id.ll_image);
        message12 = (LinearLayout)findViewById(R.id.message12);
        topbar_textview_title = (TextView) findViewById(R.id.topbar_textview_title);
        topbar_textview_title.setText("淘宝网授权");
        button_return = (Button) findViewById(R.id.button_return);
        account_tv = (EditText) findViewById(R.id.account_tv);
        et_password = (EditText) findViewById(R.id.et_password);
        bt_login = (Button) findViewById(R.id.bt_login);
        line2 = findViewById(R.id.line2);
        editTxt_msg = (EditText) findViewById(R.id.editTxt_msg);
//        editTxt_iamge = (ImageView) findViewById(R.id.editTxt_iamge);
//        view_line1 = findViewById(R.id.view_line1);
        bt_skip = (Button) findViewById(R.id.bt_skip);
        //二维码验证码,小图
        lv_msg = (ImageView) findViewById(R.id.lv_msg);
        //大图所依附的dialog
        dialog = new Dialog(TaoBaoActivity.this, R.style.AlertDialog_AppCompat_Light_);


    }



    //动态的ImageView
    private ImageView getImageView(){
        ImageView iv = new ImageView(this);
        //宽高
        iv.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        //设置Padding
        iv.setPadding(20,20,20,20);
//        InputStream   inocode   =   new   ByteArrayInputStream(in_nocode.getBytes());

        //imageView设置图片
//        InputStream is = getResources().openRawResource(inocode);
//        Drawable drawable =new BitmapDrawable(bmp);
        Drawable drawable =new BitmapDrawable(bitmap_code);
//        Drawable drawable = BitmapDrawable.createFromStream(inocode, null);
        iv.setImageDrawable(drawable);
        return iv;
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            // 要做的事情
            super.handleMessage(msg);
        }
    };
    public class MyThread implements Runnable {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (true) {
                try {
                    Thread.sleep(10000);// 线程暂停10秒，单位毫秒
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);// 发送消息
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    private void addListNer() {
        button_return.setOnClickListener(this);
        bt_login.setOnClickListener(this);
        bt_skip.setOnClickListener(this);
        lv_msg.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
//         switch (v.getId()){
//             case R.id.button_return:
////                 startActivity(new Intent(TaoBaoActivity.this,ProcessActivity.class));
//                 finish();
//                 break;
//             case R.id.bt_skip:
//                 showAlertMsgDialog("跳过此步会影响提现额度吆!", "确认", "取消");
//                 break;
//             //二维码
//             case R.id.lv_msg:
//                 dialog.show();
//                 break;
//             case R.id.bt_login:
//                 // 防止连续点击处理
//                 if (fasterClickCheck())
//                     return;
//                 account = account_tv.getText().toString().trim();
//                 pssword = et_password.getText().toString().trim();
//                 if (TextUtils.isEmpty(account)){
//                     showShortToast1("请输入账号");
//                 }
//                 if (TextUtils.isEmpty(pssword)){
//                     showShortToast1("请输入密码");
//                 }
//
//                 if (!TextUtils.isEmpty(account)&&!TextUtils.isEmpty(pssword)){
//                     if (editTxt_msg.getText().toString().trim()==null||codeX==null){
//                         try{
//                             bt_login.setEnabled(false);
//                             getDataFromServer();
//                         }catch (Exception e){
//
//                         }
//
//                     }else{
//                         try {
//                             getMsageFromServer();
//                         }catch (Exception e){
//                             e.printStackTrace();
//                         }
//
//                     }
//
//                 }
//                 break;
//         }
    }

    /**
     * 填入短信验证码后的
     */
    private void getMsageFromServer() {
        String userId = Constants.LOGIN_USER.getId().toString();
        showWaitDialog();
        if (type.equals("0")){
            //图片验证码
////            String iamge_msage = editTxt_iamge.getText().toString().trim();
//            OkHttpUtils
//                    .post()
//
//                    .url(Constants.API_ROOT + "/api/honeycomb/taobao/checkCode")
//                    .addParams("userId",userId)
//                    .addParams("username",account)
//                    .addParams("password",pssword)
//                    .addParams("checkCode",iamge_msage)
//                    .addParams("sid",sid)
//                    .addParams("mimidaiVersion",Constants.APP_VERSION)
//                    .addParams("mimidaiCode",Constants.APP_CODE + "")
//                    .addParams("token", Constants.LOGIN_USER.getToken())
//                    .build().execute(new GenericsCallback<TaoBao>(new JsonGenericsSerializator()) {
//                @Override
//                public void onError(Call call, Exception e, int id) {
//                    e.printStackTrace();
//                    showShortToast(msg);
//                }
//
//                @Override
//                public void onResponse(TaoBao response, int id) {
//                    if (response.getCode().equals("0")){
//                        msg = response.getMsg();
//                        type = response.getData().getType();
//                        showShortToast(msg);
//                        if (response.getData().getError().equals("0")){
//                            //获取检查状态
//                          //  getdataCheckStatus();
//                            //跳转到芝麻信用
//
//                        }else{
//                            if (!TextUtils.isEmpty(response.getData().getMsg())){
//                                showShortToast(response.getData().getMsg());
//                            }else {
//                                showShortToast("当前系统繁忙，请稍后再试");
//                            }
//
//                        }
//                    }
//
//                }
//            });
        }else if (type.equals("1")){
            //短信验证码
             msg_lv = editTxt_msg.getText().toString().trim();
//            post()
//
//                    .url(Constants.API_ROOT + "/api/honeycomb/taobao/checkCode")
//                    .addParams("userId",userId)
//                    .addParams("username",account)
//                    .addParams("password",pssword)
//                    .addParams("checkCode", msg_lv)
//                    .addParams("sid",sid)
//                    .addParams("mimidaiVersion",Constants.APP_VERSION)
//                    .addParams("mimidaiCode",Constants.APP_CODE + "")
//                    .addParams("token", Constants.LOGIN_USER.getToken())
//                    .build().execute(new GenericsCallback<TaoBao>(new JsonGenericsSerializator()) {
//                @Override
//                public void onError(Call call, Exception e, int id) {
//                    e.printStackTrace();
////                    showShortToast(msg);
//                }
//
//                @Override
//                public void onResponse(TaoBao response, int id) {
//                    if (response == null){
//                        showShortToast1("网络超时，请再试!");
//                        closeWaitDialog();
//                    }
//                    msg = response.getMsg();
//                    Log.i("验证码..",response.toString());
////                    showShortToast(msg);
//                    if (response.getData().getError().equals("0")){
//                        closeWaitDialog();
////                        showShortToast(response.getData().getMsg());
//                        //跳转到芝麻信用
//                      //  presenter.doCreditRequest();
//                        //检查状态
//                        getdataCheckStatus();
//
//                    }else{
//                        if (!TextUtils.isEmpty(response.getData().getMsg())){
////                            showShortToast(response.getData().getMsg());
//
//                        }else {
//                            showShortToast1("当前系统繁忙，请稍后再试");
//                            closeWaitDialog();
//                        }
//
//                    }
//                }
//            });
        }else if (type.equals("3")){
            //检查状态
            getdataCheckStatus();
        }


    }
    //检查状态
    private void getdataCheckStatus() {
//        OkHttpUtils
//                .post()
//
//                .url(Constants.API_ROOT + "/api/honeycomb/taobao/checkStatus")
//                .addParams("userId",Constants.LOGIN_USER.getId() + "")
//                .addParams("username",account)
//                .addParams("password",pssword)
//                .addParams("asid",sid)
//                .addParams("mimidaiVersion",Constants.APP_VERSION)
//                .addParams("mimidaiCode",Constants.APP_CODE + "")
//                .addParams("token", Constants.LOGIN_USER.getToken())
//                .build().connTimeOut(10000).readTimeOut(10000).writeTimeOut(10000).execute(new GenericsCallback<TaoBao>(new JsonGenericsSerializator()) {
//            @Override
//            public void onError(Call call, Exception e, int id) {
//                    e.printStackTrace();
//            }
//
//            @Override
//            public void onResponse(TaoBao response, int id) {
//                if (response == null){
//                    showShortToast1("网络超时，请再试!");
//                    closeWaitDialog();
//                }
//                if (response!=null){
//                    if (response.getCode().equals("0")){
//                        if (response.getData()!=null && response.getData().getError().equals("0")){
//                            bt_login.setEnabled(false);
//                            showWaitDialog();
//                            //跳转到芝麻信用
//                            presenter.doCreditRequest();
////                        TaoBaoActivity.this.finish();
//                        }
//
//
//                    }else if (response.getCode().equals("9")){
//                        Toast.makeText(TaoBaoActivity.this, "您的账号在另一台设备上登录", Toast.LENGTH_SHORT).show();
//                        Intent intent = new Intent(TaoBaoActivity.this, LoginActivity.class);
//                        intent.addFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
//                        startActivity(intent);
//                    }else {
//                        showShortToast1("网络异常,请稍后重试!");
//                    }
//                }
//
//
//            }
//        });

    }
    @Override
    public void toastMessage(final String msg) {
        //check context
        if(isFinishing() || TextUtils.isEmpty(msg)){
            return;
        }
        //toast message
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(TaoBaoActivity.this, msg, Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //onActivityResult callback
        CreditApp.onActivityResult(requestCode, resultCode, data);
    }

    //请求接口，得到数据
    private void getDataFromServer() {
//        String userId = Constants.LOGIN_USER.getId().toString();
        showWaitDialog();
//        post()
//
//                .url(Constants.API_ROOT + "/api/honeycomb/taobao/firstLogin")
//                .addParams("userId",Constants.LOGIN_USER.getId() + "")
//                .addParams("username",account)
//                .addParams("password",pssword)
//                .addParams("mimidaiVersion",Constants.APP_VERSION)
//                .addParams("mimidaiCode",Constants.APP_CODE + "")
//                .addParams("token", Constants.LOGIN_USER.getToken())
//                .build()
//                .execute(new GenericsCallback<TaoBao>(new JsonGenericsSerializator()) {
//                    @Override
//                    public void onError(Call call, Exception e, int id) {
//                        e.printStackTrace();
//                    }
//
//                    @Override
//                    public void onResponse(TaoBao response, int id) {
//                        if (response == null){
//                            showShortToast1("网络超时，请再试!");
//                            closeWaitDialog();
//                        }
//                        if (response!=null){
//                            closeWaitDialog();
//                        if ("0".equals(response.getCode())){
//                            if (response.getData()!=null){
//                                if (response.getData().getError().equals("0")){
//
//                                    bt_login.setEnabled(true);
//                                    TaoBao.DataBean data = response.getData();
//                                    in_nocode = data.getCodeX();
//                                    bitmap_code = stringtoBitmap(data.getCodeX());
//
//
//                                    String stdata = data.toString();
//                                    sid = data.getSid();
//
//
//                                    TaoBaoActivity.this.codeX = data.getCodeX();
//                                    String msg = response.getMsg();
//                                    type = data.getType();
//                                    try{
////
//
//                                        if (!TextUtils.isEmpty(type)){
//                                            //短信验证码
//                                            if (type.equals("1")){
//                                                message12.setVisibility(View.VISIBLE);
//                                                line2.setVisibility(View.VISIBLE);
////                                    view_line1.setVisibility(View.VISIBLE);
//                                                //图片验证码
//                                            }else if (type.equals("0")){
////                                    ll_image.setVisibility(View.VISIBLE);
////                                    line2.setVisibility(View.VISIBLE);
//                                                //扫描验证码
//                                            }else if (type.equals("3")){
//
//                                                ll_image.setVisibility(View.VISIBLE);
//                                                line2.setVisibility(View.VISIBLE);
//                                                mImageView = getImageView();
//                                                dialog.setContentView(mImageView);
//                                                lv_msg.setImageBitmap(bitmap_code);
//                                                //大图的点击事件（点击让他消失）
//                                                mImageView.setOnClickListener(new View.OnClickListener() {
//                                                    @Override
//                                                    public void onClick(View v) {
//                                                        dialog.dismiss();
//                                                    }
//                                                });
//                                                //大图的长按监听
//                                                mImageView.setOnLongClickListener(new View.OnLongClickListener() {
//                                                    @Override
//                                                    public boolean onLongClick(View v) {
//                                                        //弹出的“保存图片”的Dialog
//                                                        AlertDialog.Builder builder = new AlertDialog.Builder(TaoBaoActivity.this);
//                                                        builder.setItems(new String[]{getResources().getString(R.string.save_picture)}, new DialogInterface.OnClickListener() {
//                                                            @Override
//                                                            public void onClick(DialogInterface dialog, int which) {
//                                                                saveCroppedImage(((BitmapDrawable) mImageView.getDrawable()).getBitmap());
//                                                            }
//
//
//                                                        });
//                                                        builder.show();
//                                                        return true;
//                                                    }
//                                                });
////                                    getdataCheckStatus();
//                                            }
//                                        }
//
//                                    }catch (Exception e){
//
//                                    }
//
//                                }else {
//                                    try {
//
//                                        showShortToast1(response.getData().getMsg());
//                                        bt_login.setEnabled(true);
//                                    }catch (Exception e){
//
//                                    }
//
//                                }
//                            }
//
//
//                        }else {
//                            showShortToast1("登录失败，请稍后重试!");
//                            bt_login.setEnabled(true);
//                        }
//
//
//
//                        }
//
//
//
//                    }
//
//
//
//                });
    }


}
